package com.qidian.k12.controller;

import com.qidian.k12.dto.PageInfo;
import com.qidian.k12.pojo.Template;
import com.qidian.k12.service.TemplateService;
import com.qidian.k12.util.K12Result;
import com.qidian.k12.util.ObjectTools;
import com.qidian.k12.vo.TemplateQueryVo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.aspectj.util.FileUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * (Template)表控制层
 *
 * @author makejava
 * @since 2021-10-28 09:02:10
 */
@RestController
@RequestMapping("template")
public class TemplateController {



    /**
     * 服务对象
     */
    @Resource
    private TemplateService templateService;

    @RequestMapping("/export")
    public ResponseEntity export(TemplateQueryVo vo) throws IOException {
        // 在内存中生成excel文件
        // 读取数据
        PageInfo<Template> pageInfo = templateService.queryByPage(ObjectTools.object2map(vo));
        List<Template> temps = pageInfo.getData();
        // 生成excel
        Workbook workbook =  new XSSFWorkbook();
        // 创建sheet
        Sheet sheet = workbook.createSheet("模版列表");
        //可以先放入一行作为表头
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(0);
        // 这里可以设置单元格的样式
        cell.setCellValue("编号");
        Cell cell1 = row.createCell(1);
        cell1.setCellValue("名称");
        Cell cell2 = row.createCell(2);
        cell2.setCellValue("创建时间");
        Cell cell3 = row.createCell(3);
        cell3.setCellValue("最后修改事件");
        Cell cell4 = row.createCell(4);
        cell4.setCellValue("状态");
        // 循环temps,一行一行的放入
        for (int x = 0;x < temps.size();x++){
            Template t = temps.get(x);
            // 创建行
            Row r = sheet.createRow(x + 1);
            Cell c = r.createCell(0);
            c.setCellValue(t.getTemplateId());
            Cell c1 = r.createCell(1);
            c1.setCellValue(t.getTemplateName());
            Cell c2 = r.createCell(2);
            c2.setCellValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(t.getCreateTime()));
            Cell c3 = r.createCell(3);
            c3.setCellValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(t.getModifyTime()));
            Cell c4 = r.createCell(4);
            c4.setCellValue(t.getTemplateStatus()==1?"正常":"废弃");
        }
        // 准备一个读写内存的流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        // 将这个数据写入输出流
        workbook.write(out);
        byte [] buff = out.toByteArray();
        // 准备一些响应头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("content-Disposition","attachment;fileName=templates.xlsx");
        httpHeaders.add("content-length",buff.length+"");
        ResponseEntity entity = new ResponseEntity(buff,httpHeaders, HttpStatus.OK);
        return entity;
    }


    @RequestMapping("/downLoadTemplate")
    public ResponseEntity downLoadTemplate(HttpServletRequest request) throws IOException {
        // 获取服务器路径
        String serverPath = request.getServletContext().getRealPath("/");
        File file = new File(serverPath+"template.xlsx");

        // 准备一些响应头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("content-Disposition","attachment;fileName=template.xlsx");
        httpHeaders.add("content-length",file.length()+"");
        ResponseEntity entity = new ResponseEntity(FileUtil.readAsByteArray(file),httpHeaders, HttpStatus.OK);
        return entity;
    }


//    public void downLoadTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        // 获取服务器路径
//        String serverPath = request.getServletContext().getRealPath("/");
//        File file = new File(serverPath+"template.xlsx");
//        InputStream in = new FileInputStream(file);
//        // response的相关设置
//        response.setHeader("content-Disposition","attachment;fileName=template.xlsx");
//        response.setHeader("content-length",file.length()+"");
//        // 得到输出流
//        ServletOutputStream out = response.getOutputStream();
//        // 文件拷贝的操作
//        int len = -1;
//        byte [] buff = new byte[1024];
//        while((len = in.read(buff))!=-1){
//            out.write(buff);
//            out.flush();
//        };
//        out.close();
//        return;
//    }

    @RequestMapping("/import")
    public K12Result importTemplate(@RequestParam("template") CommonsMultipartFile template) throws IOException {
        // 获取指向临时文件的输入流
        InputStream in = template.getInputStream();
        // 将输入流传入service进行解析处理
        return templateService.importTemplate(in,template.getOriginalFilename());
    };

    @RequestMapping("/query")
    public PageInfo<Template> query(TemplateQueryVo vo){
        return templateService.queryByPage(ObjectTools.object2map(vo));
    }

    @PostMapping("/save")
    public K12Result save(@RequestBody Template template){
        return templateService.insert(template);
    };

    @GetMapping("/get")
    public Template get(long templateId){
        return templateService.queryById(templateId);
    }
    @PostMapping("/update")
    public K12Result update(@RequestBody Template template){
        return templateService.update(template);
    };

    @GetMapping("/queryByName")
    public K12Result queryByName(String templateName){
        return templateService.queryByName(templateName);
    }
}

